package main

import (
	"log"
	"net/http"
	"sync"

	"github.com/gorilla/websocket"
)

// WebSocket upgrader
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

// Clients map to store connected WebSocket clients
var clients = make(map[*websocket.Conn]bool)

type Message struct {
	Sender *websocket.Conn
	Data   []byte
}

var broadcast = make(chan Message)

var mutex = &sync.Mutex{}

func main() {
	http.HandleFunc("/ws", handleConnections)

	go handleMessages()

	log.Println("Signaling server started on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
	// Upgrade initial GET request to a WebSocket
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Printf("Error upgrading connection: %v", err)
		return
	}
	defer ws.Close()

	// Register client
	mutex.Lock()
	clients[ws] = true
	mutex.Unlock()

	for {
		var msg []byte
		_, msg, err = ws.ReadMessage()
		if err != nil {
			log.Printf("Error reading message: %v", err)
			mutex.Lock()
			delete(clients, ws)
			mutex.Unlock()
			break
		}
		log.Printf(string(msg))
		// Broadcast message to other clients
		broadcast <- Message{Sender: ws, Data: msg}
	}
}

func handleMessages() {
	for {
		msg := <-broadcast

		// Send message to all connected clients
		mutex.Lock()
		for client := range clients {
			// 跳过发送者
			if client == msg.Sender {
				continue
			}

			err := client.WriteMessage(websocket.TextMessage, msg.Data)
			if err != nil {
				log.Printf("Error sending message: %v", err)
				client.Close()
				delete(clients, client)
			}
		}
		mutex.Unlock()
	}
}
